package com.googlecode.pwlodars.piteststat.content;

import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

public class PackageInfo {

	private int id;
	
	private String name;
	
	private PackageInfo parentPackage;

	public PackageInfo(String packagePath) {
		this.name = packagePath;
		parentPackage=resolveParent(packagePath);
	}

	public PackageInfo(int id, String packagePath) {
		this(packagePath);
		this.id = id;
	}

	public static PackageInfo resolveParent(String fullPath){
		int indexOfLastDot = fullPath.lastIndexOf(".");
		if(indexOfLastDot==-1){
			return null;
		}
		return new PackageInfo(fullPath.substring(0, indexOfLastDot));
	}
	
	public PackageInfo getParent(){
		return parentPackage;
	}
	
	public String findChildPart(String fullClassName) {
		return fullClassName.replaceAll(name+".", "");
	}
	
	public List<PackageInfo> getHierarchyPackages() {
		StringTokenizer tokenizer=new StringTokenizer(name, ".");
		return resolveSubPackages(tokenizer);
		
	}

	private List<PackageInfo> resolveSubPackages(StringTokenizer tokenizer) {
		StringBuilder subPackageName=new StringBuilder();
		List<PackageInfo> packages=new LinkedList<PackageInfo>();
		while(tokenizer.hasMoreTokens()){
			subPackageName.append(tokenizer.nextToken());
			packages.add(new PackageInfo(subPackageName.toString()));
			subPackageName.append(".");
		}
		return packages;
	}

	public String getName() {
		return name;
	}

	public boolean hasParent() {
		return parentPackage!=null;
	}
	
	public int getId() {
		return id;
	}

	@Override
	public String toString() {
		return "PackageInfo [name=" + name + "]";
	}
	
	
}
